package shopping

import (
	"errors"
	"fmt"
	"dhfshop/models/org"
	"dhfshop/models"
	"dhfshop/models/consts"
	"strings"
	"time"
	"github.com/astaxie/beego/orm"
)

/* 售后单 */
type ReturnForm struct {
    PartnerId     int64         `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"`
	ReturnFormId  string        `orm:"column(return_form_id);size(64);pk" json:"return_form_id" form:"return_form_id"`        /*  */
    CreatorUser   *org.User     `orm:"rel(fk);column(creator_id);on_delete(do_nothing)" json:"-" form:"-"`   /* 录入者*/
    CreatorId     int64         `orm:"-" json:"creator_id" form:"-"`         
    CreatedAt     time.Time     `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`   /* 创建时间 */
	CreatedAtStr  string        `orm:"-" json:"created_at" form:"-"`
	UpdatedAt     time.Time     `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"` 
	UpdatedAtStr  string        `orm:"-" json:"updated_at" form:"-"`
	TypeId        int64         `orm:"column(type_id)" json:"type_id,omitempty" form:"-"`        //动态计算
	Status        string        `orm:"column(status);size(32)" json:"status" form:"status"`       //可选：已创建、已审核、已作废 
	Tid           string        `orm:"column(tid);size(64)" json:"tid" form:"tid"`       /*原订单号*/    
	ReasonId      int64         `orm:"column(reason_id)" json:"reason_id" form:"reason_id"`  /*退换原因 */
	ShippingType  string        `orm:"column(shipping_type);size(64);null" json:"shipping_type" form:"shipping_type"` /*物流方式名称，是否需要外键关联？*/
	LogisticsNo   string        `orm:"column(logistics_no);size(64);null" json:"logistics_no" form:"logistics_no"` /*运单号：登记客户退换货运单号，便于到货时定位*/
	//
	BuyerAccount   string    `orm:"column(buyer_account);size(50);index" json:"buyer_account" form:"buyer_account"` /* 账户 */
	ReturnItemFee  float32   `orm:"column(return_item_fee);digits(12);decimals(2)" json:"return_item_fee" form:"return_item_fee"`  /*退货金额*/
	OutItemFee     float32   `orm:"column(out_item_fee);digits(12);decimals(2)" json:"out_item_fee" form:"out_item_fee"` /*出货金额*/
	ReplenishFee   float32   `orm:"column(replenish_fee);digits(12);decimals(2)" json:"replenish_fee" form:"replenish_fee"` /*客户补款金额*/
	RefundFee      float32   `orm:"column(refund_fee);digits(12);decimals(2)" json:"refund_fee" form:"refund_fee"`           /*商家退款金额*/
	OtherFee       float32   `orm:"column(other_fee);digits(12);decimals(2)" json:"other_fee" form:"other_fee"`           /*邮资费用等其他费用*/
	TotalFee       float32   `orm:"column(total_fee);digits(12);decimals(2)" json:"total_fee" form:"total_fee"`  /* 合计金额*/
	ReturnPoint   int32         `orm:"column(return_point);size(32);null" json:"return_point" form:"return_point"` /*返还积分*/
	// 客户
	BuyerNick        string     `orm:"column(buyer_nick);size(64)" json:"buyer_nick" form:"buyer_nick"`                 // 会员
	ReceiverState    string     `orm:"column(receiver_state);size(32);null" json:"receiver_state" form:"receiver_state"`         
    ReceiverCity     string     `orm:"column(receiver_city);size(256);null" json:"receiver_city" form:"receiver_city"`
    ReceiverDistrict string     `orm:"column(receiver_district);size(256);null" json:"receiver_district" form:"receiver_district"`
	ReceiverAddress  string     `orm:"column(receiver_address);size(256);null" json:"receiver_address" form:"receiver_address"`
    ReceiverMobile   string     `orm:"column(receiver_mobile);size(32);null" json:"receiver_mobile" form:"receiver_mobile"`            
	ReceiverName     string     `orm:"column(receiver_name);size(32);null" json:"receiver_name" form:"receiver_name"` 
    ReceiverPhone  string `orm:"column(receiver_phone);size(32);null" json:"receiver_phone" form:"receiver_phone"`                             
    ReceiverZip      string     `orm:"column(receiver_zip);size(32);null" json:"receiver_zip" form:"receiver_zip"`  
	Remark           string          `orm:"column(remark);size(256);null" json:"remark" form:"remark"`    /* 备注 */
	InItems      []*ReturnFormItem   `orm:"reverse(many)" json:"in_items"`               /*退入商品明细*/                
	InItemJson    string             `orm:"-" json:"-" form:"in_items"`                            
	OutItems     []*ReplaceFormItem  `orm:"reverse(many)" json:"out_items"`              /*换出商品明细*/             
	OutItemJson   string             `orm:"-" json:"-" form:"out_items"`   
}

/* 退入商品明细 */
type ReturnFormItem struct {
	PartnerId    int64         `orm:"column(partner_id);index" json:"partner_id"`
    ReturnItemId int64       `orm:"column(return_item_id);pk;auto" json:"return_item_id"`           /* 编号 */
	ReturnForm   *ReturnForm `orm:"column(return_form_id);rel(fk);on_delete(cascade)" json:"-"`     /*  */
	ReturnFormId string       `orm:"-" json:"return_form_id"`                                         /*  */
    ItemID       int64       `orm:"column(item_id)" json:"item_id,omitempty"`                                  /* 商品ID */
    SkuId        int64       `orm:"column(sku_id)" json:"sku_id,omitempty"`                                    /* 商品Sku的id */
	Num          int32       `orm:"column(num);null" json:"num,omitempty"`                                      /* 数量*/
	Price        float32     `orm:"column(price);digits(12);decimals(2)" json:"price,omitempty"`                /* 单价 */
	DiscountFee  float32     `orm:"column(discount_fee);digits(12);decimals(2)" json:"discount_fee,omitempty"`  /* 优惠金额 */
    Payment      float32     `orm:"column(payment);digits(12);decimals(2)" json:"payment,omitempty"`            /* 金额 */
	Remark       string      `orm:"column(remark);size(256);null" json:"remark,omitempty" form:"remark"`                  /* 备注 */
}

/* 换出商品明细 */
type ReplaceFormItem struct {
	PartnerId     int64         `orm:"column(partner_id);index" json:"partner_id"`
    ReplaceItemId int64       `orm:"column(replace_item_id);pk;auto" json:"replace_item_id"`           /* 编号 */
	ReturnForm    *ReturnForm `orm:"column(return_form_id);rel(fk);on_delete(cascade)" json:"-"`       /*  */
	ReturnFormId  string       `orm:"-" json:"return_form_id"`                                          /*  */
    ItemID        int64       `orm:"column(item_id)" json:"item_id,omitempty"`                                   /* 商品ID */
    SkuId         int64       `orm:"column(sku_id)" json:"sku_id,omitempty"`                                     /* 商品Sku id */
	Num           int32       `orm:"column(num);null" json:"num,omitempty"`                                      /* 数量*/
	Price         float32     `orm:"column(price);digits(12);decimals(2)" json:"price,omitempty"`                /* 单价 */
	DiscountFee   float32     `orm:"column(discount_fee);digits(12);decimals(2)" json:"discount_fee,omitempty"`  /* 优惠金额 */
    Payment       float32     `orm:"column(payment);digits(12);decimals(2)" json:"payment,omitempty"`            /* 金额 */
	Remark        string      `orm:"column(remark);size(256);null" json:"remark,omitempty" form:"remark"`                  /* 备注 */
}

func init() {
    orm.RegisterModel(new(ReturnForm),new(ReturnFormItem),new(ReplaceFormItem))
}

func AddReturnForm(m *ReturnForm) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddReturnFormItem(m *ReturnFormItem) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddReturnFormItems(list []*ReturnFormItem) (err error) {
    o := models.GetDefaultDB()
    size := len(list)
	if size > 1 {
	    _, err = o.InsertMulti(size, list) 
	}else{
	   _, err = o.Insert(list[0])
	}	
	return
}

func AddReplaceFormItem(m *ReplaceFormItem) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}
func AddReplaceFormItems(list []*ReplaceFormItem) (err error) {
    o := models.GetDefaultDB()
    size := len(list)
	if size > 1 {
	    _, err = o.InsertMulti(size, list) 
	}else{
	   _, err = o.Insert(list[0])
	}	
	return
}

func GetReturnFormById(id string) (v *ReturnForm, err error) {
	o := models.GetDefaultDB()
	v = &ReturnForm{ReturnFormId: id}
	if err = o.Read(v); err == nil {
	    o.LoadRelated(v, "InItems")
		for _, item := range v.InItems {
			item.ReturnForm = nil
		}
		o.LoadRelated(v, "OutItems")
		for _, item := range v.OutItems {
			item.ReturnForm = nil
		}
		v.CreatedAtStr = v.CreatedAt.Format(consts.DATETIME_FORMAT)
		v.UpdatedAtStr = v.UpdatedAt.Format(consts.DATETIME_FORMAT)
		return v, nil
		return v, nil
	}
	return nil, err
}

func GetAllReturnForms(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*ReturnForm,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ReturnForm))
	if start, ok := query["start_created"]; ok {
		if startTime, err := time.Parse(consts.DATELINKTIME_FORMAT, start); err == nil {
		    qs = qs.Filter("created_at__gte", startTime)
		}
		delete(query, "start_created")
	}
	if end, ok := query["end_created"]; ok {
		if endTime, err := time.Parse(consts.DATELINKTIME_FORMAT, end); err == nil {
	        qs = qs.Filter("created_at__lte", endTime)
	    }
		delete(query, "end_created")
	}
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*ReturnForm
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
	    for _, form := range lists {
	        o.LoadRelated(form, "InItems")
			for _, item := range form.InItems {
			    item.ReturnFormId = item.ReturnForm.ReturnFormId
			    item.ReturnForm = nil
		    }
		    o.LoadRelated(form, "OutItems")
			for _, item := range form.OutItems {
			    item.ReturnFormId = item.ReturnForm.ReturnFormId
			    item.ReturnForm = nil
		    }
			form.CreatedAtStr = form.CreatedAt.Format(consts.DATETIME_FORMAT)
			form.UpdatedAtStr = form.UpdatedAt.Format(consts.DATETIME_FORMAT)
		}
		return lists, cnt, nil
	}
	return nil, 0, err
}
	
func UpdateReturnFormById(m *ReturnForm, param ...string) (err error) {
	o := models.GetDefaultDB()
	v := ReturnForm{ReturnFormId: m.ReturnFormId}
	if err = o.Read(&v); err == nil {
		_, err = o.Update(m, param...)
		return
	}
	return
}

func UpdateReturnFormItemById(m *ReturnFormItem, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := ReturnFormItem{ReturnItemId: m.ReturnItemId}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m, k...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func UpdateReplaceFormItemById(m *ReplaceFormItem, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := ReplaceFormItem{ReplaceItemId: m.ReplaceItemId}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m, k...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func DeleteReturnForm(id string) (err error) {
	o := models.GetDefaultDB()
	v := ReturnForm{ReturnFormId: id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&v); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

